'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const collection = db.collection('accessToken');
	let list = await collection.get();
	let appid = "wxa12be3aa044494d5"; //你自己的appid
	let secret = "012527a5282e57b69bda0760562e7549"; //你自己的appsecret
	let url =
		"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +
		appid +
		"&secret=" +
		secret;

	let tokenData = {};
	let nowDate = new Date().getTime();
	if (list.data.length === 0) {
		let res = await uniCloud.httpclient.request(
			url, // 请求路径,
			{
				dataType: "json"
			}
		);
		let data = res.data;
		tokenData = {
			date: nowDate,
			...data
		};
		if (res.status === 200 && data) {
			collection.add(tokenData);
		}
	} else {
		let data = list.data[0];
		console.log(nowDate);
		if (nowDate - data.date < 3600 * 1000) {
			tokenData = data;
		} else {
			let res = await uniCloud.httpclient.request(
				url, // 请求路径,
				{
					dataType: "json"
				}
			);
			let tokenRes = res.data;
			tokenData = {
				date: nowDate,
				...data
			};
			if (res.status === 200 && data) {
				let uploadRes = await collection.doc(data._id).update({
					access_token: tokenRes.access_token,
					date: nowDate
				});
			}
		}
	}
	// {"data":{"access_token":"78_rQqrWGOxbcWBXr1yhqNYjDzEsRbenCpZdUPizpJ44A5NPosvmlNjObnTA2W66p5tXwokVN53eY1eN-5DUPZ4rVYR1ieVVlfmxgfU1u2LQwFbPb8coN7R0qo4-R4PAWhACAFQM","expires_in":7200},"status":200,"headers":{"connection":"keep-alive","content-type":"application/json; encoding=utf-8","date":"Sat, 0
	// accessToken
	console.log(JSON.stringify(tokenData));
	//返回数据给客户端
	return tokenData;
};